//通过这个 类watcher 来实现更新

import { pushTarget, popTarget } from "./dep"
let id = 0
class Watcher {
  constructor(vm, updateComponent, cb, optins) {
    this.vm = vm
    this.exprOrfn = updateComponent
    this.cb = cb
    this.optins = optins
    this.deps = [] //watcher存放dep
    this.depsId = new Set()
    this.id = id++

    if (typeof updateComponent === 'function') {
      this.getter = updateComponent //用来更新视图的

    }
    this.get()
  }
  addDep(dep) {
    //去重
    let id = dep.id
    if (!this.depsId.has(id)) {
      this.deps.push(dep)
      this.depsId.add(id)
      dep.addSub(this)
    }
  }
  //初次渲染 在生命周期文件中执行
  get() {
    pushTarget(this) //给dep添加watcher
    this.getter() //渲染页面 vm._update(vm._render())
    popTarget() //给dep移除watcher
  }

  //更新
  update() {
    this.get()
  }
}
export default Watcher

//收集依赖 vue dep watcher data:{name,msg}
//dep dep和data中的属性是一一对应的，有多少个属性就有多少个dep
//watcher 在视图上用几个(如name)，就用几个watcher
//dep与watcher：一对多，dep.name